// 基础JavaScript功能
document.addEventListener('DOMContentLoaded', function() {
    // 导航栏激活状态管理
    setActiveNavLink();
    
    // 用户下拉菜单功能
    initUserDropdown();
    
    // AI聊天功能
    if (typeof window.initAIChat === 'function') {
        window.initAIChat();
    }
    
    // 页面特定的初始化
    const currentPath = window.location.pathname;
    if (currentPath === '/') {
        initHomePage();
    } else if (currentPath === '/notifications') {
        // 通知页面功能由 notifications.js 模块处理
        if (typeof window.initNotificationsPage === 'function') {
            window.initNotificationsPage();
        }
    } else if (currentPath === '/profile') {
        if (typeof window.initProfilePage === 'function') {
        initProfilePage();
        }
    }
});

// ===== 竞赛详情全局函数（供聊天与历史记录/竞赛列表共用）=====
// 若页面已定义则不重复定义
if (!window.getBadgeClassAndText) {
    window.getBadgeClassAndText = function(rating) {
        const hasRating = rating !== undefined && rating !== null && String(rating).trim() !== '';
        if (!hasRating || String(rating).trim() === '?' || String(rating).trim().toLowerCase() === 'unknown') {
            return { badgeClass: 'unknown', ratingText: '?' };
        }
        const ratingUpper = String(rating).toUpperCase();
        let cls = ratingUpper;
        if (ratingUpper.includes('+')) {
            cls = ratingUpper.replace('+', 'plus');
        } else if (ratingUpper.includes('-')) {
            cls = ratingUpper.replace('-', 'minus');
        }
        return { badgeClass: cls, ratingText: ratingUpper };
    };
}

if (!window.formatDate) {
    window.formatDate = function(dateString) {
        if (!dateString) return '待定';
        try {
            const date = new Date(dateString);
            if (isNaN(date.getTime())) return '待定';
            return date.toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' });
        } catch (e) {
            return '待定';
        }
    };
}

if (!window.getStatusText) {
    window.getStatusText = function(status) {
        switch (status) {
            case 'ongoing': return '进行中';
            case 'upcoming': return '即将开始';
            case 'finished': return '已结束';
            default: return '未知状态';
        }
    };
}

if (!window.copyCompetitionDetail) {
    window.copyCompetitionDetail = function(competitionName, detail) {
        const textToCopy = `竞赛名称：${competitionName}\n\n详细信息：\n${detail}`;
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(textToCopy).then(() => {
                if (typeof window.showCopySuccess === 'function') window.showCopySuccess();
            }).catch(err => {
                console.error('复制失败:', err);
                if (typeof window.fallbackCopyTextToClipboard === 'function') window.fallbackCopyTextToClipboard(textToCopy);
            });
        } else {
            if (typeof window.fallbackCopyTextToClipboard === 'function') window.fallbackCopyTextToClipboard(textToCopy);
        }
    };
}

if (!window.fallbackCopyTextToClipboard) {
    window.fallbackCopyTextToClipboard = function(text) {
        const textArea = document.createElement('textarea');
        textArea.value = text;
        textArea.style.position = 'fixed';
        textArea.style.left = '-999999px';
        textArea.style.top = '-999999px';
        document.body.appendChild(textArea);
        textArea.focus();
        textArea.select();
        try {
            document.execCommand('copy');
            if (typeof window.showCopySuccess === 'function') window.showCopySuccess();
        } catch (err) {
            console.error('回退复制失败:', err);
            if (typeof window.showCopyError === 'function') window.showCopyError();
        }
        document.body.removeChild(textArea);
    };
}

if (!window.showCopySuccess) {
    window.showCopySuccess = function() {
        const toast = document.createElement('div');
        toast.className = 'copy-toast success';
        toast.innerHTML = `
            <iconify-icon icon="material-symbols:check-circle" width="20"></iconify-icon>
            <span>详细信息已复制到剪贴板</span>
        `;
        document.body.appendChild(toast);
        setTimeout(() => { toast.classList.add('show'); }, 100);
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => { if (document.body.contains(toast)) document.body.removeChild(toast); }, 300);
        }, 3000);
    };
}

if (!window.showCopyError) {
    window.showCopyError = function() {
        const toast = document.createElement('div');
        toast.className = 'copy-toast error';
        toast.innerHTML = `
            <iconify-icon icon="material-symbols:error" width="20"></iconify-icon>
            <span>复制失败，请手动复制</span>
        `;
        document.body.appendChild(toast);
        setTimeout(() => { toast.classList.add('show'); }, 100);
        setTimeout(() => {
            toast.classList.remove('show');
            setTimeout(() => { if (document.body.contains(toast)) document.body.removeChild(toast); }, 300);
        }, 3000);
    };
}

if (!window.showCompetitionDetail) {
    window.showCompetitionDetail = function(competition) {
        const modal = document.createElement('div');
        modal.className = 'competition-modal';
        const badgeInfo = window.getBadgeClassAndText ? window.getBadgeClassAndText(competition.rating) : { badgeClass: 'unknown', ratingText: '?' };
        const badgeClass = badgeInfo.badgeClass;
        const ratingText = badgeInfo.ratingText;
        const searchInput = document.getElementById('searchInput');
        const searchQuery = searchInput ? searchInput.value.trim() : '';
        const highlightText = (text, query) => {
            if (!query) return text;
            const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
            return String(text || '').replace(regex, '<mark class="search-highlight">$1</mark>');
        };
        modal.innerHTML = `
            <div class="modal-overlay">
                <div class="modal-content">
                    <div class="modal-header">
                        <h2>${competition.name}</h2>
                        <span class="detail-badge ${badgeClass}">${ratingText}</span>
                        <button class="modal-close">&times;</button>
                    </div>
                    <div class="modal-body">
                        <div class="info-row">
                            <span class="info-label">主办方：</span>
                            <span class="info-value">${competition.organizer}</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">状态：</span>
                            <span class="info-value"><span class="status-badge ${competition.status}">${window.getStatusText ? window.getStatusText(competition.status) : ''}</span></span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">时间：</span>
                            <span class="info-value">${window.formatDate ? window.formatDate(competition.start_date) : ''} - ${window.formatDate ? window.formatDate(competition.end_date) : ''}</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">分类：</span>
                            <span class="info-value">${(competition.categories || []).join('、')}</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">团队规模：</span>
                            <span class="info-value">最多 ${competition.max_team_size} 人</span>
                        </div>
                        <div class="info-row">
                            <span class="info-label">评级：</span>
                            <span class="info-value"><span class="detail-badge ${badgeClass}">${ratingText}</span></span>
                        </div>
                        <div class="description-section">
                            <h3>竞赛详情</h3>
                            <p>${competition.detail ? highlightText(competition.detail, searchQuery) : (competition.description || '')}</p>
                        </div>
                    </div>
                    <div class="modal-actions">
                        <button class="btn btn-primary" onclick="window.open('${competition.url}', '_blank')">
                            <iconify-icon icon="material-symbols:link" width="16"></iconify-icon>
                            访问官网
                        </button>
                        ${competition.detail ? `
                        <button class="btn btn-secondary" onclick="window.copyCompetitionDetail('${competition.name.replace(/'/g, "\\'")}', \`${String(competition.detail).replace(/`/g, '\\`')}\`)">
                            <iconify-icon icon="material-symbols:content-copy" width="16"></iconify-icon>
                            复制详情
                        </button>
                        ` : ''}
                        <button class="btn btn-secondary modal-close-btn">关闭</button>
                    </div>
                </div>
            </div>
        `;
        document.body.appendChild(modal);
        const closeModal = () => { if (document.body.contains(modal)) document.body.removeChild(modal); };
        modal.querySelector('.modal-close').addEventListener('click', closeModal);
        modal.querySelector('.modal-close-btn').addEventListener('click', closeModal);
        modal.querySelector('.modal-overlay').addEventListener('click', (e) => { if (e.target === modal.querySelector('.modal-overlay')) closeModal(); });
    };
}


// 设置导航栏激活状态
function setActiveNavLink() {
    const currentPath = window.location.pathname;
    const navLinks = document.querySelectorAll('.nav-link');
    
    navLinks.forEach(link => {
        link.classList.remove('active');
        if (link.getAttribute('href') === currentPath) {
            link.classList.add('active');
        }
    });
}

// 首页初始化
function initHomePage() {
    // 搜索功能
    const searchInput = document.getElementById('searchInput');
    const searchBtn = document.getElementById('searchBtn');
    const categoryFilter = document.getElementById('categoryFilter');
    const statusFilter = document.getElementById('statusFilter');
    const clearFiltersBtn = document.getElementById('clearFilters');
    
    // 搜索按钮点击事件
    if (searchBtn) {
        searchBtn.addEventListener('click', performSearch);
    }
    
    // 回车键搜索
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                performSearch();
            }
        });
    }
    
    // 筛选器变化事件
    if (categoryFilter) {
        categoryFilter.addEventListener('change', performSearch);
    }
    
    if (statusFilter) {
        statusFilter.addEventListener('change', performSearch);
    }
    
    // 清除筛选
    if (clearFiltersBtn) {
        clearFiltersBtn.addEventListener('click', function() {
            if (searchInput) searchInput.value = '';
            if (categoryFilter) categoryFilter.value = '';
            if (statusFilter) statusFilter.value = '';
            // 清除排序选项
            const sortFilter = document.getElementById('sortFilter');
            if (sortFilter) sortFilter.value = '';
            performSearch();
        });
    }
    
    // 执行搜索
    function performSearch() {
        const query = searchInput ? searchInput.value : '';
        const category = categoryFilter ? categoryFilter.value : '';
        const status = statusFilter ? statusFilter.value : '';
        
        // 构建查询参数
        const params = new URLSearchParams();
        if (query) params.append('q', query);
        if (category) params.append('category', category);
        if (status) params.append('status', status);
        
        // 重新加载竞赛数据
        loadCompetitions(`/api/competitions/search?${params.toString()}`);
    }
    
    // 视图切换
    const viewBtns = document.querySelectorAll('.view-btn');
    const competitionsContainer = document.getElementById('competitions-container');
    
    viewBtns.forEach(btn => {
        btn.addEventListener('click', function() {
            const view = this.dataset.view;
            
            // 更新按钮状态
            viewBtns.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            // 切换视图
            if (competitionsContainer) {
                competitionsContainer.className = `competitions-${view}`;
            }
        });
    });
}

// 添加消息提示样式
const style = document.createElement('style');
style.textContent = `
    .message-toast {
        position: fixed;
        top: 20px;
        right: 20px;
        padding: 12px 20px;
        border-radius: 6px;
        color: white;
        font-size: 14px;
        font-weight: 500;
        z-index: 1000;
        transform: translateX(100%);
        transition: transform 0.3s ease;
    }
    
    .message-toast.show {
        transform: translateX(0);
    }
    
    .message-toast.success {
        background: #10B981;
    }
    
    .message-toast.error {
        background: #EF4444;
    }
    
    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateY(20px);
        }
        to {
            opacity: 1;
            transform: translateY(0);
        }
    }
`;
document.head.appendChild(style);

// 用户下拉菜单功能
function initUserDropdown() {
    const userInfoDropdown = document.getElementById('userInfoDropdown');
    const userDropdown = document.getElementById('userDropdown');
    
    if (!userInfoDropdown || !userDropdown) return;
    
    // 点击用户信息区域切换下拉菜单
    userInfoDropdown.addEventListener('click', function(e) {
        e.stopPropagation();
        userInfoDropdown.classList.toggle('active');
    });
    
    // 点击页面其他地方关闭下拉菜单
    document.addEventListener('click', function(e) {
        if (!userInfoDropdown.contains(e.target)) {
            userInfoDropdown.classList.remove('active');
        }
    });
    
    // 点击下拉菜单项时关闭菜单
    const dropdownItems = userDropdown.querySelectorAll('.dropdown-item');
    dropdownItems.forEach(item => {
        item.addEventListener('click', function() {
            userInfoDropdown.classList.remove('active');
        });
    });
    
    // ESC键关闭下拉菜单
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            userInfoDropdown.classList.remove('active');
        }
    });
}